import axios from 'axios'

import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import Config from '@/settings'
import md5 from '@/utils/js-md5/build/md5.min.js';
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: Config.timeout // request timeout
})

//生成key
function generateKey(timestamp,data) {
  // 去除不存在的参数
  Object.keys(data).forEach(item => {
    if (data[item] === undefined) {
      delete data[item];
    }
  });
  let newParams = ksort(data)
  let key = ""
  for (let i in newParams) {
    key += i;
  }
  key = key+timestamp + 'WdEz2T1oSvruN8eQqLU3xiZYJwycBaMA'
  key = encodeURI(key)
  key = md5(key)
  return key
}

//按升序排序参数
function ksort(params) {
  let keys = Object.keys(params).sort();
  let newParams = {};
  keys.forEach((key) => {
    newParams[key] = params[key];
  });
  return newParams;
}

function parseQuery(url) {
  url = url || '';
  const queryObj = {};
  const reg = /[?&]([^=&#]+)=([^&#]*)/g;
  const queryArr = url.match(reg) || [];
  for (const i in queryArr) {
    if (Object.hasOwnProperty.call(queryArr, i)) {
      const query = queryArr[i].split('=');
      const key = query[0].substr(1);
      const value = decodeURIComponent(query[1]);
      queryObj[key] ? queryObj[key] = [].concat(queryObj[key], value) : queryObj[key] = value;
    }
  }
  return queryObj;
}
// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    var  data=''
    if(config.method=='get'){
      if(config.params) {
        data = config.params
      }else {
        data =parseQuery(config.url)
      }
    }else if(config.data) {
      data =config.data
    }
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['token'] = getToken()
      var timestamp = Date.parse(new Date()).toString();
      timestamp = timestamp.substring(0, timestamp.length - 3);
      config.headers['sign'] =generateKey(timestamp,data)
      config.headers['timestamp'] =parseInt(timestamp)
    }
    // config.headers['Content-Type'] = 'application/json'
    config.headers['Content-Type'] = 'application/json;charset=UTF-8'
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data

    // if the custom code is not 20000, it is judged as an error.

    if (res.code !== 0) {
      if (response.data instanceof Blob) {
        return res
      }
      // Message({
      //   message: res.msg || 'Error',
      //   type: 'error',
      //   duration: 5 * 1000
      // })

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;

      if (res.code === 406) {
        // to re-login
        MessageBox.confirm('您已登出或没有权限访问，请重新登录', '确认登出', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('resetToken').then(() => {
            location.reload()
          })
        })
      } else if (res.code === 401) {
        // to re-login
        MessageBox.confirm(res.msg, '确认登出', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // store.dispatch('LogOut').then(() => {
          //   location.reload()
          // })

          store.dispatch('resetToken').then(() => {
            location.reload()
          })
        })
      } else {
        Message({
          message: res.msg || 'Error',
          type: 'error',
          duration: 5 * 1000
        })
      }

      return Promise.reject(new Error(res.msg || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.msg,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
